/******************************************************************************
 * Copyright (c) 2014 - 2016. Danlu.com Co.Ltd. All rights reserved.          *
 ******************************************************************************/

package cn.com.dhc.danlu.util;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;

import java.lang.reflect.Type;
import java.util.Date;

/**
 * Create GSON with initial factors.
 *
 * @author guodong@dhc.com.cn
 */
public class GsonFactory {

    private static GsonBuilder gsonBuilder = null;

    /**
     * Create GsonBuilder
     */
    private static synchronized GsonBuilder getGsonBuilder() {
        if (gsonBuilder == null) {
            gsonBuilder = new GsonBuilder();
            gsonBuilder.registerTypeAdapter(Date.class, new MillisecondsDateTypeAdapter());
        }
        return gsonBuilder;
    }

    /**
     * Create GSON
     */
    public static Gson getGson() {
        return getGsonBuilder().create();
    }

    /**
     * Implementation of DateTypeAdapter for parsing milliseconds to Date.
     */
    private static class MillisecondsDateTypeAdapter implements JsonSerializer<Date>, JsonDeserializer<Date> {
        @Override
        public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext context) {
            return new JsonPrimitive(src.getTime());
        }

        @Override
        public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
            return new Date(json.getAsLong());
        }
    }
}